package com.ityun.ogapp.fragment

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.ityun.ogapp.App
import com.ityun.ogapp.adapter.ContactAdapter
import com.ityun.ogapp.base.BaseFragment
import com.ityun.ogapp.data.ContactBean
import com.ityun.ogapp.databinding.FragmentContactBinding
import com.ityun.ogapp.dialog.AddContactDialogFragment
import com.ityun.ogapp.vm.ContactModel

class ContactFragment : BaseFragment<FragmentContactBinding>() {

    private val mViewModel by lazy {
        ContactModel(App.context)
    }

    private val adapter by lazy {
        ContactAdapter()
    }


    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentContactBinding {
        return FragmentContactBinding.inflate(inflater, container, false)
    }

    override fun initViews() {
        super.initViews()
        setRcv()
    }

    override fun initData() {
        super.initData()
        mViewModel.loadContact()
    }

    override fun subscribe() {
        super.subscribe()
        mViewModel.allContacts.observe(this) {
            val contactBean = ContactBean(-1, "", "", "", "")
            val list = it?.toMutableList()?.apply { add(contactBean) } ?: mutableListOf(contactBean)
            adapter.setNewInstance(list)
        }
    }

    private fun setRcv() {
        mBinding.rvContact.layoutManager = GridLayoutManager(this.context, 3)
        mBinding.rvContact.adapter = adapter

        // 设置Item点击事件
        adapter.setOnItemClickListener { adapter, view, position ->
            if (position == adapter.data.size - 1) {
                val dialogFragment = AddContactDialogFragment.newInstance()
                dialogFragment.show(parentFragmentManager, "AddContactDialog")
            } else {

            }
        }
    }

}
